// 引入接口文件
import { getProjectList,queryUserByPorject,submit,queryInfo,verifyCodeFun } from './userAddServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  modelObj: {
    btnLoading: false,
  },
  selectData: [],
  loading: false,
  actionType: 'add',
  appRoleZituo: '',
  areaList: [],
  products: [],
  tempArr : [],
  selectOptionData: [],
  parentIdList: [],
  parentId:'',
  checkAll: false,
  query: {
    // companyName: '', //区域名称
    areaId: [],
    // projectId: '',
    // projectName: '',
    appRoleZituo: '',
    userType: '',
    phone: '',
    name: '',
    bankCode: '', //银行卡号
    idCode: '', //身份证号
    bankName: '', //开户行
    projectIdList: [],
    parentId:'', //归属人
  },
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({type: 'verifyCodeFun',payload: {query}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录
    *queryInfo({payload}, {put, select, call}){
      let {parentIdList,query,selectData,appRoleZituo} = yield select(state => state[tmpModule.namespace])
      let params = { "id":payload.query.id }
      // let params = { "id": 'testSave' }
      if(yield call(verifyCodeFun,{})){
        const { success, msg, data } = yield call(queryInfo, {...params})
        if(data == "{}"){
          return
        }
        if(success){
          // let dat = JSON.parse(data)
          let dat = data
            appRoleZituo =  dat.user.appRoleZituo
            query = dat.user
            query.areaId = dat.user.companyId !='null'&&!!dat.user.companyId?dat.user.companyId.split(","): ''
            let areaIds = dat.user.companyId
            query['projectIdList'] = []
            let list  = dat.user.orgList
            let parentIdlist = []
            for(var item of list){
              let obj = {}
              query.projectIdList.push(item.orgId)
              obj.userId = item.zituoParentid
              obj.projectId = item.orgId
              selectData.push(obj)
              parentIdlist.push(item.zituoParentid)
            }
            query.parentId = parentIdlist.join(',')
            yield put({
              type: 'updateStore',
              payload: {query,selectData,appRoleZituo}
            })
            yield put({
              type: 'getProjectList',
              payload: {areaId:areaIds}
            })
        }
      }
    },
    //获取区域项目
    *getProjectList({payload},{put,select,call}){
      let {areaList} = yield select(state => state[tmpModule.namespace])
      let params = {
        level : 2
        }
      if(yield call(verifyCodeFun,{})){
        const { data } = yield call(getProjectList, {...params})
          let list = data
          if(!list.length){
            return
          }
          areaList =  list.map((item,index)=>{
              return {
                label: item.buname,
                value: item.buguid,
                children: item.childSysUninessunitList
              }
          })
          yield put({type: 'updateStore', payload: {areaList}})
          if(payload.areaId){
            yield put({type: 'filterProjectList', payload: {areaId:payload.areaId}})
          }
        }
      },
    //获取归属人
    *queryUserByPorject({payload},{put,select,call}){
      let {selectOptionData,products,query} = yield select(state => state[tmpModule.namespace])
      if(!!payload.type){
        for(var item of query.projectIdList){
          let params = {
            projectId: item
          }
          let { success,data } = yield call(queryUserByPorject, {...params})
          if(success){
            let list = data
            if(!list.userList.length){
              return
            }
            selectOptionData =  list.userList.map((item,index)=>{
              return {
                label: item.name,
                value: item.id,
              }
            })
            for(var tt of products){
              if(tt.value == item){
                tt.selectOptionData= selectOptionData
              }
            }
          }
        }
        yield put({type: 'updateStore', payload: {selectOptionData,products}})
      }
      if(!!payload.id){
        let params = {
          projectId: payload.id
        }
        let { success,data } = yield call(queryUserByPorject, {...params})
        if(success){
          let list = data
          // let list = JSON.parse(data)
          if(!list.userList.length){
            return
          }
          selectOptionData =  list.userList.map((item,index)=>{
            return {
              label: item.name,
              value: item.id,
            }
          })
          for(var tt of products){
            if(tt.value == payload.id){
              tt.selectOptionData= selectOptionData
            }
          }
          yield put({type: 'updateStore', payload: {selectOptionData,products}})
        }
        }
      },
    *filterProjectList({payload},{put,select,call}){    
      let {checkAll,query,products,areaList,selectData,appRoleZituo} = yield select(state => state[tmpModule.namespace])
      let list = []
      let areaIds= payload.areaId.split(',')
      for(var item of areaList){
        for(var itemed of areaIds){
           if(item.value == itemed){
            list.push(...item.children)
          }
        }
      }
      if(list.length){
        products =  list.map((item,index)=>{
          return {
            label: item.buname,
            value: item.buguid,
            userId: '',
            selectOptionData: [],
          }
        })
      }
      if(!!selectData.length&&appRoleZituo == '4'){
        for(var tt of products){
          for(var it of selectData){
            if(tt.value == it.projectId){
              tt['userId'] = it.userId
              yield put({type: 'updateStore', payload: {products}})
              yield put({type: 'queryUserByPorject', payload: {id:it.projectId}})
            }
          }
        }
      }
      checkAll = query.projectIdList.length === products.length
      yield put({type: 'updateStore', payload: {products,checkAll}})
    },
    *submit({payload,callback},{put,select,call}){
      let {query,actionType} = yield select(state => state[tmpModule.namespace])
      if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(query.phone))){ 
        message.warn("手机号码有误");  
        return false; 
      } 
      if(query.appRoleZituo == '4'){
        
        if(query.idCode&&!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(query.idCode))){ 
          message.warn("身份证号码有误");  
          return false; 
        } 
        if(query.bankCode&&!(/^([1-9]{1})(\d{14}|\d{18})$/.test(query.bankCode))){ 
          message.warn("银行卡号有误");  
          return false; 
        } 
      }else{
        query.idCode = ''
        query.bankCode = ''
        query.bankName = ''
      }
      
      query.position = ''
      let params = query
      const { success, msg, data } = yield call(submit, {...params})
      if(success){
        if(actionType == 'add'){
          message.success('新增成功')
        }else if(actionType == 'detail'){
          message.success('修改成功')
        }
        callback();
      }
    },
    *verifyCodeFun({payload},{put,select,call}){
      if(yield call(verifyCodeFun,{})){
        if (payload.query.actionType == 'detail') {
          yield put({type: 'queryInfo',payload: payload})
        }
        yield put({type: 'getProjectList', payload: {actionType: payload.query.actionType,id: payload.query.id, } })
      }
    }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
